<template>
  <div class="dialog">
    <el-dialog title="用户注册" width="603px" :visible="isShow" center>
      <el-form ref="form" :model="form" :rules="rules" label-width="70px">
        <el-form-item label="头像" prop="avatar">
          <div class="photo">
            <el-upload
              v-model="form.avatar"
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="httpRequest"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
            <!-- 删除图片按钮 -->
            <div v-if="imageUrl" class="del" @click="close">x</div>
          </div>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password />
        </el-form-item>
        <el-form-item label="图形码" prop="code">
          <div class="graphCode">
            <el-input v-model="form.code" class="input" />
            <div class="graph" @click="graphChange">
              <img :src="graphCode" alt="">
            </div>
          </div>
        </el-form-item>
        <el-form-item label="验证码" prop="rcode">
          <div class="graphCode">
            <el-input v-model="form.rcode" class="input" />
            <div class="getCode">
              <el-button type="primary" @click="getCodeEvent">
                <span v-if="codeShow">获取验证码</span>
                <span v-if="!codeShow">{{ count }}秒后重试</span>
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="delEvent">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { validPhone } from '@/utils/validate.js'
import { uploads, sendsms, register } from '@/api/login.js'
import { Message } from 'element-ui'

export default {
  data() {
    return {
      show: false,
      codeShow: true, // 判断显示隐藏
      count: '', // 显示时的文字内容
      TIME_COUNT: 10, // 倒计时
      timer: null,
      isShow: false,
      imageUrl: '',
      graphCode: process.env.VUE_APP_BASE_API + '/captcha?type=sendsms',
      form: {
        username: '', //	是	string	用户名
        email: '', //	是	string	邮箱
        phone: '', //	是	string	手机号
        password: '', //	是	string	密码
        avatar: '', //	是	string	头像地址
        rcode: '', //	是	string	验证码
        code: ''
      },
      rules: {
        username: [{ required: true, message: '必填', trigger: 'change' }],
        phone: [
          { required: true, message: '必填', trigger: 'change' },
          {
            min: 11,
            max: 11,
            trigger: 'change',
            message: '请输入正确的手机号'
          },
          {
            validator: (rules, value, callback) => {
              validPhone(value)
                ? callback()
                : callback(new Error('请输入正确的手机号'))
            }
          }
        ],
        email: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rules, value, callback) => {
              const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的邮箱号'))
              }
            }
          }
        ],
        avatar: [{ required: true, message: '必填', trigger: 'change' }],
        password: [
          { required: true, trigger: 'change', message: '请输入密码' },
          {
            min: 6,
            max: 12,
            trigger: 'change',
            message: '请输入6-12位密码'
          }
        ],
        rcode: [{ required: true, message: '必填', trigger: 'change' }],
        code: [
          { required: true, trigger: 'change', message: '请输入验证码' },
          {
            min: 4,
            max: 4,
            trigger: 'change',
            message: '请输入验证码'
          }
        ]
      }
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    async httpRequest(file) {
      const fd = new FormData()
      fd.append('image', file.file)
      const res = await uploads(fd)
      console.log('fd', res)

      this.form.avatar = 'http://' + res.data.data.file_path
    },

    // 取消头像上传
    close() {
      this.imageUrl = ''
    },

    // 取消按钮
    delEvent() {
      this.isShow = false
    },
    // 点击图形码时获取新的图形码
    graphChange() {
      const src = this.graphCode
      this.graphCode = ''
      this.$nextTick(() => {
        this.graphCode = src
      })
    },
    // 获取短信验证码按钮
    async getCodeEvent() {
      const res = await sendsms({
        code: this.form.code,
        phone: this.form.phone
      })
      this.rcode = res.data.data.captcha
      Message.success(res.data.data.captcha + '')
      console.log('验证码', res)

      // 验证码倒计时
      if (!this.timer) {
        this.count = this.TIME_COUNT
        this.codeShow = false
        // this.opacity = 0.45
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= this.TIME_COUNT) {
            this.count--
            this.TIME_COUNT = this.count
          } else {
            this.codeShow = true
            // this.opacity = 0
            clearInterval(this.timer)
            this.timer = null
            this.TIME_COUNT = 6
          }
        }, 1000)
      }
    },
    // 注册按钮
    async submit() {
      const res = await register(this.form)
      console.log('注册', res)

      Message.success('注册成功')
      this.isShow = false
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog {
  height: 100%;
  ::v-deep .el-dialog__header {
    background-color: #07b6fa;
  }
  ::v-deep i.el-dialog__close.el-icon.el-icon-close {
    display: none;
  }
  .avatar-uploader {
    margin-bottom: 24px;
  }
  .el-input {
    width: 489px;
    height: 39px;
    //   margin-left: 12px;
  }
  .el-form-item {
    margin-bottom: 24px;
  }
  .photo {
    position: relative;
    .del {
      position: absolute;
      top: 0;
      right: 130px;
      height: 30px;
      width: 30px;
      // font-size: 14px;
      color: #ccc;
      cursor: pointer;
      // display: none;
    }
    &:hover {
      .del {
        display: block;
      }
    }
    text-align: center;
    i.el-icon-plus.avatar-uploader-icon {
      border: 1px dashed #d9d9d9;
    }
    .avatar-uploader .el-upload {
      //   border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .graphCode {
    width: 489px;
    display: flex;
    .input {
      width: 325px;
      height: 100%;
    }
    .graph,
    .getCode {
      width: 143px;
      height: 39px;
      margin-left: 21px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
